/**
 * 产品分类列表
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var laydate = layui.laydate;
    var cols = [
        [
            {field: 'staffId', type: 'checkbox', fixed: 'left', width: 50, align: 'center'},
            {
                field: 'sort',
                title: '排序号',
                fixed: 'left',
                width: 60,
                align: 'center',
                edit: json.hasSort ? 'text' : false,
                unresize: true,
                sort: false
            },
            {field: 'staffId', title: '员工ID', fixed: 'left', width: 100, align: 'center', unresize: true, sort: false},
            {field: 'staffName', title: '账号', fixed: 'left',  width: 100,align: 'center', unresize: true, sort: false},
            {field: 'realName', title: '真实姓名', fixed: 'left', width: 100, align: 'center', unresize: true, sort: false},
            {field: 'staffNumber', title: '工号',  width: 75, align: 'center', unresize: true, sort: false},
            {field: 'dtalkId', title: '钉钉userId',  width: 175, align: 'center', unresize: true, sort: false},
            {field: 'archivesNumber', title: '档案号', width: 100, align: 'center', unresize: true, sort: false},
            {field: 'companyName', title: '合同公司', width: 175, align: 'center', unresize: true, sort: false, templet:d=>{
                    if (d.companyName) {
                        return d.companyName;
                    } else {
                        return "--";
                    }
                }},
            {field: 'deptName', title: '部门', width: 175, align: 'center', unresize: true, sort: false, templet:d=>{
                    if (d.deptName && d.positionName) {
                        return d.deptName;
                    } else if (d.positionName) {
                        return d.positionName;
                    } else {
                        return "--";
                    }
                }},
            {field: 'positionName', title: '岗位', width: 175, align: 'center', unresize: true, sort: false, templet:d=>{
                    if (d.positionName) {
                        return d.positionName;
                    } else {
                        return "--";
                    }
                }},
            {
                field: 'positionLevel', title: '职级', width: 175, align: 'center', unresize: true, templet: function (d) {
                if (d.positionLevel) {
                    return zmnEnum.STAFF_LEVEL[d.positionLevel];
                } else {
                    return "--";
                }
            }
            },

            {
                field: 'sexType', title: '性别', width: 60, align: 'center', unresize: true, templet: function (d) {
                    if (d.sexType == 1) {
                        return "男";
                    } else if (d.sexType == 2) {
                        return "女";
                    } else {
                        return "--";
                    }
                }
            },

            {field: 'mobile', title: '手机号', width: 165, align: 'center', unresize: true, sort: false, templet:d=>{
                if (d.mobile) {
                    return d.mobile;
                } else {
                    return "--";
                }
                }},

            {field: 'bankCardNoVarchar', title: '银行卡号', width: 160, align: 'center', unresize: true, sort: false},

            {
                field: 'type', title: '员工类型', width: 125, align: 'center', unresize: true, templet: function (d) {
                    return zmnEnum.STAFF_TYPE[d.roleType];
                }
            },

            {
                field: 'entryTime', title: '入职时间', templet: '#entryTime', width: 125, align: 'center', unresize: true,
                templet: function (row) {
                    let str = zmnUtil.createTime(row.entryTime);
                    if (str.length > 10) {
                        return str.substr(0, 10);
                    } else {
                        return str;
                    }
            }
            },
            {
                field: 'becomeFormalTime', title: '转正时间', templet: '#becomeFormalTime', width: 125, align: 'center', unresize: true,
                templet: function (row) {
                    let str = zmnUtil.createTime(row.becomeFormalTime);
                    if (str.length > 10) {
                        return str.substr(0, 10);
                    } else {
                        return str;
                    }
            }
            },

            {field: 'lengthOfService', title: '工龄', width: 90, align: 'center', unresize: true, sort: false},

            {
                field: 'contractEndTimeNow', title: '合同到期时间', templet: '#contractEndTimeNow', width: 125, align: 'center', unresize: true,
                templet: function (row) {
                    let str = zmnUtil.createTime(row.contractEndTimeNow);
                    if (str.length > 10) {
                        return str.substr(0, 10);
                    } else {
                        return str;
                    }
                }
            },

            {
                field: 'status', title: '状态', width: 100, align: 'center', unresize: true, templet: function (d) {
                return zmnEnum.STAFF_STATUS[d.staffStatus];
            }
            },

            {
                field: 'createrAndTime', title: '创建人/创建时间', templet: '#createrAndTime', width: 195, align: 'center', unresize: true,
                templet: d=> {
                    return d.creater + '/' + zmnUtil.createTime(d.createTime);
                }
            },
            {field: 'updaterAndUpdateTime', title: '修改人/修改时间', width: 195, align: 'center', unresize: true, templet:d=>{
                if (d.updater) {
                    return d.updater + '/' + zmnUtil.createTime(d.updateTime);
                } else {
                    return "--";
                }
            }},

            {
                fixed: 'right', title: '操作', width: 55, toolbar: '#barDemo',
            },
        ]
    ];

    table.render({
        elem: "#zmn-staff-table",
        toolbar: "#zmn-staff-table-tool",
        title: "员工花名册",
        data: json.items,
        limit: json.pageSize,
        cols: cols,
        page: true,
        height: 'full-235'
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#entryTimeRange',
        range: true,
        format: 'yyyy/MM/dd',
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#becomeFormalTimeRange',
        range: true,
        format: 'yyyy/MM/dd',
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#contractEndTimeNowRange',
        range: true,
        format: 'yyyy/MM/dd',
    });

    laypage.render(zmnPage.laypageOptions(json));

    $("[id^=showMenu-]").click(function () {
        var staffId = this.id.split('-')[1];
        var staffName = $(this).attr("staffName");
        $("#toolBar").html("<div class='layui-btn-container'>" +
            "" + (json.hasTempPwd ? "<button  onclick='tempPwd(" + staffId + ")'  class='layui-btn layui-btn-sm layui-btn-normal' >临时密码</button>" : '') +
            "" + (json.hasEdit ? "<a lay-href='/mc/staff/detail.action?staffId=" + staffId + "'><button  class='layui-btn layui-btn-sm layui-btn-normal' >编辑</button></a>" : '') +
            "" + (json.hasRoleView ? "<a lay-href='/mc/role/staff/list.action?staffId=" + staffId + "'><button  class='layui-btn layui-btn-sm layui-btn-normal' >角色</button></a>" : '') +
            "" + (json.hasStaffPermit ? "<a lay-href='/mc/staff/staffPermitList.action?staffId=" + staffId + "'><button  class='layui-btn layui-btn-sm layui-btn-normal' >数据权限</button></a>" : '') +
            "" + (json.hasOpenIpLoginToday ? "<button id='openIpBtn-" + staffName + "' name='" + staffName + "'  class='layui-btn layui-btn-sm layui-btn-normal' >不限日期</button>" : '') +
            "" + (json.hasOpenWhitelist ? "<button id='whitelistBtn-" + staffName + "' name='" + staffId + "'  class='layui-btn layui-btn-sm layui-btn-normal' >IP白名单</button>" : '') +
            "" + (json.hasOpenIpLoginToday ? "<button id='bindingEngineer' value='" + staffId + "' class='layui-btn layui-btn-sm layui-btn-normal' >绑定工程师</button>" : '') +
            "" + (json.hasSynchroDingTalk ? "<button onclick='synchroDingTalk(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' >同步钉钉</button>" : '') +
            "" + (json.hasLeave ? "<button onclick='toLeave(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' >离职</button>" : '') +
            "" + (json.hasStaffChange ? "<a lay-href='/staff/staffchangelog/list.action?staffId=" + staffId + "'><button class='layui-btn layui-btn-sm layui-btn-normal' >员工异动记录</button>" : '') +
            "</div>");
        indexTips = layer.tips($("#toolBar").html(), this, {
            shade: [0],
            shadeClose: true,
            area: ['350px', '260px'],
            time: 0, //20秒后自动关闭
            tips: [3, '#FFFFFF'],
        });
        $("[id^=openIpBtn]").click(function () {
            var staffName = this.name;
            // openIpLoginToday(staffName);
            openIpLoginDate(staffName);
        });
        //白名单设置
        $("[id^=whitelistBtn]").click(function () {
            var staffId = this.name;
            // openIpLoginToday(staffName);
            openWhitelistBtn(staffId);
        });

        $("[id^=bindingEngineer]").click(function () {
            var staffId = this.value;
            openBindingEngineerWindow(staffId);
        });
    });


    var ids = new Array();

    // 选择（全选或单选）
    table.on("checkbox(zmn-staff-table)", function () {
        ids = zmnPage.layIdsChecked(json.items, "staffId");
    });

    // 启用/停用
    table.on("toolbar(zmn-staff-table)", function (obj) {
        if (obj.event == "start" && obj.event == "stop" && obj.event == "resetPwd" && ids.length === 0) {
            return layer.alert("请选择至少一个要操作的员工！");
        }
        if (obj.event == "start" || obj.event == "stop") {
            zmnPage.layStartStop(obj, "/mc/staff/updateStatus.action", ids.join(","));
        } else if (obj.event == "resetPwd") {
            zmnPage.ajaxSimple("/mc/staff/resetPwd.action", {id: ids.join(",")}, 2500);
        }

    });

    // 修改排序
    table.on("edit(zmn-staff-table)", function (obj) {
        zmnPage.laySort(obj, "/mc/staff/updateSort.action", obj.data.staffId);
    });
    $(document).on('click', '#rebuildStaffIndex ', function () {
        let shadeIndex;
        $.ajax({
            type: "POST",
            url: "/mc/staff/rebuildStaffIndex.action",
            headers: {
                Accept: "application/json"
            },
            contentType: "application/json",
            dataType: "json",
            beforeSend: function () {

                shadeIndex = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                layer.close(shadeIndex);
                layer.msg(json.message);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.close(shadeIndex);
            }
        });
    });

    /**
     * 描述:打开绑定工程师窗口
     *
     * @author wangjie
     * @since  2019/9/23
     **/
    let openBindingEngineerWindow = function (staffId) {
        zmnLayUtil.openIframeCustom(layui.layer, "/mast/master/openBindingEngineerWindow.action?staffId=" + staffId, {
            area: ['35%', '50%'],
            title: "绑定工程师",
            shade: 0.8
        });
    };

    let formSelects = layui.formSelects;
    form.on("select(companyId)", function (obj) {
        if (zmnUtil.isNull(obj) || obj.value == 0) {
            return;
        }
        initSelect(formSelects, obj.value);
        layui.formSelects.render();
    });

    if (json.vo.companyId) {
        initSelect(formSelects, json.vo.companyId);
    }

    //对外暴露的接口
    exports('art_staff_list', {});

});

function importStaffPerformance() {
    zmnLayUtil.openIframeCustom(layer, "/mc/staff/toimportperformanceexcel.action", {title: "导入员工绩效", shade: 0.8, area:["450px", "180px"]});
}

function openIpLoginToday(staffName) {
    layui.$.post("/mc/staff/openIpLoginDate.action", {staffName: staffName}, function (res) {
        res ? layer.alert("设置成功！") : layer.alert("设置失败！");
    })
}

/**
 * 描述: 弹出ip不限时间段页面
 *
 * @author wangjie
 * @since 9:52 2019/5/31
 **/
function openIpLoginDate(staffName) {
    zmnLayUtil.openIframeCustom(layui.layer, "/mc/staff/openIpLoginDateList.action?staffName=" + staffName, {
        area: ['35%', '50%'],
        title: "设置不限日期",
        shade: 0.8
    });
}
/**
 * 描述: 弹出设置白名单页面
 *
 * @author wangjie
 * @since 9:52 2019/5/31
 **/
function openWhitelistBtn(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, "/mc/staff/openWhiteList.action?staffId=" + staffId, {
        area: ['500px', '300px'],
        title: "登录白名单",
        shade: 0.8
    });
}


/**
 * 添加临时密码
 *
 * @param staffId
 */
function tempPwd(staffId) {
    layer.open({
        type: 1,
        skin: 'layui-layer-rim',
        area: ['300px', '200px'],
        content: '<div class="layui-fluid"><input id="inputTempPwd" maxlength="12" minlength="6" class="layui-input" style="width:260px;"></div>',
        btn: ['确定'],
        yes: function (index, layero) {
            var $ = layui.$;
            var pwd = $("#inputTempPwd").val();
            var reg = new RegExp("^[0-9a-zA-Z]+$");

            if (!reg.test(pwd)) {
                layer.alert("密码只能是数字、字母");
                return false;
            }
            if (pwd == null || pwd.length < 6) {
                layer.alert("密码长度最少6位");
                return false;
            }

            if (pwd == null || pwd.length > 12) {
                layer.alert("密码长度最多12位");
                return false;
            }

            $.ajax({
                type: "POST", url: "/mc/staff/temporaryPwd.action",
                dataType: "json", data: {"id": staffId, "pwd": pwd},
                success: function (json) {
                    layer.close(index);
                    layer.alert(json.message);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.close(index);
                    layer.alert("添加失败，请联系系统管理员！");
                }
            });

            return true;
        }
    });

}

function initSelect(formSelects, companyId) {

    formSelects.config('deptId', {
        keyName: 'value',
        keyVal: 'key',
        keyChildren: 'list',
        success: function (id, url, val, result) {
            formSelects.value('deptId', [json.vo.deptId]);
        },
        error: function (id, url, val, err) {
            console.log(id + ":" + err);
        }
    });

    /**
     * 1.多选数据赋值
     *
     * formSelects.data(ID, type, config);
     *
     * @param ID            xm-select的值
     * @param type          'local' | 'server', 本地数据或者远程数据
     * @param config        配置项
     *          arr             本地数据数组
     *          url             远程数据链接
     *          keyword         远程数据搜索内容, 其他附加数据可以使用 formSelects.config设置
     *          linkage         是否为联动多选（就是把上级地扯关联一起显示/选择，true时必须全择到最底层一条线才行）
     *          linkageWidth    联动多选没级宽度
     */
    formSelects.data('deptId', 'server', {
        url: '/mc/dept/findDeptByCompanyId.action?companyId=' + companyId,
        linkage: false,
        linkageWidth: 130
    });

    formSelects.render();
}

function toLeave(staffId) {
    layui.$.ajax({
        type: "GET", url: '/staff/dingtalk/leave.action',
        dataType: "json", data: {staffId: staffId},
        success: function (result) {
            console.log(result);
            if (result.status == 121706) {
                layui.layer.msg(result.message);
                return false;
            }

            if(result.status == 121701){
                layui.layer.msg("员工异常，请联系管理员【121701】");
                return false;
            }

            if(result.status == 121704){
                layui.layer.msg("员工异常，请联系管理员【121704】");
                return false;
            }

            if(result.status == 121707){
                layui.layer.msg("员工钉钉ID不存在，请先同步钉钉【121707】");
                return false;
            }

            if(result.status == 121705){
                layui.layer.msg("请先在钉钉操作离职【121705】");
                return false;
            }

            if(result.status == 200){
                let url = "/staff/staffleaveoffice/addEditView.action?staffId=" + staffId;
                parent.layui.index.openTabsPage(url, "离职信息");
                return false;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layui.layer.alert("系统异常");
        }
    });
}

function synchroDingTalk(staffId) {
    layui.$.ajax({
        type: "GET", url: '/staff/dingtalk/synchro.action',
        dataType: "json", data: {staffId: staffId},
        success: function (result) {
            console.log(result);
            if (result.status == 200) {
                layui.layer.msg(result.message);
                return false;
            }

            if(result.status == 121701){
                layui.layer.msg("员工异常，请联系管理员【121701】");
                return false;
            }

            if(result.status == 121702){
                toSetDingTalkId(staffId);
                return false;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layui.layer.alert("系统异常");
        }
    });
}

function toSetDingTalkId(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, "/staff/dingtalk/toSetDingTalkId.action?staffId=" + staffId, {
        area: ['500px', '300px'],
        title: "从钉钉同步",
        shade: 0.8
    });
}